import { AuthGuard, IAuthGuard } from '@nestjs/passport';
import {
  CanActivate,
  ExecutionContext,
  Injectable,
  Inject,
  UnauthorizedException,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { AuthService } from '../../auth/auth.service';
import { UserService } from '../../user/user.service';
import { Reflector } from '@nestjs/core';
import type { Request } from 'express';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(@Inject(Reflector) private readonly reflector: Reflector) {
    super();
  }
  canActivate(context: ExecutionContext) {
    // const role = this.reflector.get<string[]>('role', context.getHandler());
    // const req = context.switchToHttp().getRequest<Request>();
    // console.log(role, req.query.role);

    const isNoAuth = this.reflector.getAllAndOverride('isNoAuth', [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isNoAuth) return true;
    const guard = new (AuthGuard('jwt'))();
    return guard.canActivate(context); //  执行所选策略Guard的canActivate方法
  }

  //   async canActivate(context: ExecutionContext): Promise<boolean> {
  //     console.log('进入全局守卫');
  //     const req = context.switchToHttp().getRequest();
  //     const res = context.switchToHttp().getResponse();
  //     // @如果白名单数组中存在路径
  //     if (this.hasUrl(this.urlList, req.url)) return true;
  //     const guard = new (AuthGuard('jwt'))();
  //     return guard.canActivate(context) as boolean; //  执行所选策略Guard的canActivate方法
  //   }
  //   // 白名单数组
  //   private urlList: string[] = ['/auth/login', '/user/create'];
  //   // 验证该次请求是否为白名单内的路由
  //   private hasUrl(urlList: string[], url: string): boolean {
  //     let flag = false;
  //     if (urlList.indexOf(url) !== -1) {
  //       flag = true;
  //     }
  //     console.log('------------》', url, flag);
  //     return flag;
  //   }
}
